package net.aaa.hotel.controller;

import com.alibaba.fastjson.JSON;
import net.aaa.hotel.dao.HRoleDao;
import net.aaa.hotel.dao.impl.HRoleDaoImpl;
import net.aaa.hotel.entity.HRole;
import net.aaa.hotel.util.BaseDB;
import net.aaa.hotel.util.TransBean;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/role")
public class HRoleController extends HttpServlet {
    private HRoleDao dao = new HRoleDaoImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html; charset=UTF-8");
        String method = req.getParameter("method");
        if(method!=null){
            switch (method){
                case "add":
                    addDept(req,resp);
                    break;
                case "del":
                    delDept(req,resp);
                    break;
            }

        }else {
            List<Map> maps = dao.findAll();
            Map m = new HashMap();
            m.put("code",0);
            m.put("msg","");
            m.put("count",maps.size());
            m.put("data",maps);
            String string = JSON.toJSONString(m);
            PrintWriter out = resp.getWriter();
            out.write(string);
        }
    }

    private void delDept(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String gid = req.getParameter("gid");
        int i = dao.delRole(gid);
        resp.sendRedirect("role/show.jsp");
    }

    private void addDept(HttpServletRequest req, HttpServletResponse resp) {
        Map<String, String[]> parameterMap = req.getParameterMap();
        HRole ro = new HRole();
        TransBean.populate(ro,parameterMap);
        int i =  dao.addRole(ro);
    }
}
